"""
    Various HTML-related functions
"""
from __future__ import with_statement

import pango
import urllib

from . import log
from . import path
from . import exceptions
from . import strunicode as su

files_cache = dict()
html_templates = None

rating_titles = None

def gen_html_page(body="", head="", title=""):
         
    skel = get_html_template("base")
    return skel % {
        'css_common': 'file://' + path.get_data_path("html", "css", "common.css"),
        'css_auto': 'file://' + path.auto_css_file(), 
        'css_user': 'file://' + path.get_config_path("user.css"), 
        'head': head,
        'js': 'file://' + path.javascript_file(),
        'body': body,
        'title': title
        }

def get_cached_data(file):
    """
        Return cached file contents
    """
    global files_cache
    log.debug("Get cached content of file `%s'" % file)

    if not files_cache.has_key(file):
        # load data
        files_cache[file] = "/* */"
        try:
            f = open(file)
            files_cache[file] = f.read()
            f.close()
        except IOError, e:
            log.error(e)

    return files_cache[file]

def request_url_handler(widget, url, stream):
    log.debug("URL `%s' requested" % url)
    
    use_cache = False
    file = None
    
    if url.startswith("file://"):
        file = url[7:]
        use_cache = False
        #stream.write(f.read())
        #stream.close()
    elif url.startswith("css://"):
        file = path.get_data_path("html", "css", url[len("css://"):])
        use_cache = True
    elif url.startswith("stockimg://"):
        file = path.get_data_path("images", url[len("stockimg://"):])
        use_cache = True
    
    if use_cache:
        data = get_cached_data(file)
    else:
        try:
            f = open(file)
            data = f.read()
            f.close()
        except IOError, e: 
            log.error(e)
    
    stream.write(data)
    stream.close()

#def set_html(doc, body="", head=""):
#    """
#        Set new content of html browser object
#    """
#    content = gen_html_page(body, head)
#    doc.render_data(content, long(len(content)), "file:///", "text/html")

def get_html_templates():
    """
        Return dict with all html templates
    """
    global html_templates
    
    if html_templates is None:
        # build templates dict
        templates = ("general_search_results", "general_search_results_author", 
                     "general_search_results_book", "book", "book_author", "base",
                     "book_genre", "book_series", "genre_author", "series_author", 
                     "author", "author_book", "genre", "series", "series_book", 
                     "genre-author", "genre-author_book", "stats", "stats_genres", 
                     "stats_general_item", "stats_genres_genre", "shelves",
                     "shelves_shelf", "shelf", "shelf_book", "shelf_book_author")
        html_templates = dict()
        
        for t in templates:
            file = path.get_data_path("html", "templates", t+".html")
            try:
                f = open(file)
                html_templates[t] = f.read()
                f.close() 
            except IOError:
                html_templates[t] = "[broken template]"
        
    return html_templates

def get_html_template(name):
    """
        Return template for given template name
    """
    templates = get_html_templates()
    if not templates.has_key(name):
        raise exceptions.HtmlTemplateError("No such template: %s" % name)
    
    return html_templates[name]

def stock_img_url(img):
    return "file://" + path.get_data_path("images", img)


def update_javascript_file():
    
    file = path.javascript_file()
    
    try:
        orig_file = path.get_data_path("html", "javascript.js")
        f = open(orig_file)
        orig = f.read()
        f.close()
        
        orig = orig % {
            'star_on': stock_img_url("star.png"),
            'star_off': stock_img_url("star-bw.png")
            }
        
        f = open(file, "w")
        f.write(orig)
        f.close()
    except IOError, e:
        log.error("IOError: %s" % e)
        
def update_auto_css_file(normal_font, headers_font, background_color, hover_links_color):
    auto_css = path.auto_css_file()
    
    def fontname_to_css(font_name, no_size=False):
        """
        Convert gtk fontname into css rules
        
        @return: CSS rules, without curly braces
        """
        res = ""
        pf = pango.FontDescription(font_name)
        
        ff = pf.get_family()
        if ff.lower() == "sans":
            ff = "sans-serif"
        elif ff.lower() == "serif":
            ff = "serif"
        else:
            ff = '"%s"' % ff
        res += " font-family: %s; " % ff
        
        if not no_size:
            size = pf.get_size()
            if not pf.get_size_is_absolute():
                size = (size / pango.SCALE)
                
            res += " font-size: %spt; " % size
        
        return res
        
    def gtk_color_to_css(color):
        return "#%02X%02X%02X" % tuple([x/255 for x in (color.red, color.green, color.blue) ])
    
    try:
        
        f = open(auto_css, "w")
        with f:
            f.write("/* THIS FILE IS AUTOMATICALLY GENERATED! DO NOT EDIT! */\n\n")
            pf = pango.FontDescription(normal_font)
            f.write("body, p, div { %s background-color: %s }\n\n" % (
                fontname_to_css(normal_font), gtk_color_to_css(background_color) )) 
            f.write("h1, h2, h3, h4, h5, h6 { %s }\n\n" % fontname_to_css(headers_font, True))
            f.write("a:hover { %s }" % gtk_color_to_css(hover_links_color))
            
    except IOError, e:
        log.error("IOError: %s" % e)

def get_rating_titles():        
    global rating_titles
    
    if rating_titles is None:
        rating_titles = (
        _("Poor"),
        _("So-so"),
        _("Average"),
        _("Pretty good"),
        _("Awesome!")
        )    
    
    return rating_titles

def quote(s):
    """
    Encode unicode/unicode-encode str into the %XX form
    
    @param s: str or unicode object
    """
    if isinstance(s, unicode):
        s = su.unicode2ustr(s)
        
    return urllib.quote(s)
    
def unquote(s):
    """
    Decode
    
    @param s: str
    """
    return su.ustr2unicode(urllib.unquote(s))
    
    
    
    
    
    
    
    
    
    
    
